﻿using System.Reflection;
using System.Text;

namespace Borg
{
    public class VersionInfo
    {
        private readonly Assembly _assembly;

        public string Title
        {
            get
            {
                var customAttributes =
                    _assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);

                return
                    customAttributes.Length > 0
                        ? ((AssemblyTitleAttribute) customAttributes[0]).Title
                        : string.Empty;
            }
        }

        public string Product
        {
            get
            {
                var customAttributes =
                    _assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);

                return
                    customAttributes.Length > 0
                        ? ((AssemblyProductAttribute) customAttributes[0]).Product
                        : string.Empty;
            }
        }

        public string InformationalVersion
        {
            get
            {
                var customAttributes =
                    _assembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false);

                return
                    customAttributes.Length > 0
                        ? ((AssemblyInformationalVersionAttribute) customAttributes[0]).InformationalVersion
                        : string.Empty;
            }
        }

        public string FileVersion
        {
            get
            {
                var customAttributes =
                    _assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);

                return
                    customAttributes.Length > 0
                        ? ((AssemblyFileVersionAttribute) customAttributes[0]).Version
                        : string.Empty;
            }
        }

        public string Copyright
        {
            get
            {
                var customAttributes =
                    _assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);

                return
                    customAttributes.Length > 0
                        ? ((AssemblyCopyrightAttribute) customAttributes[0]).Copyright
                        : string.Empty;
            }
        }

        internal VersionInfo(Assembly assembly)
        {
            _assembly = assembly;
        }

        public override string ToString()
        {
            var builder = new StringBuilder();
            
            builder.AppendLine(string.Format("{0} Version {1}", Title, FileVersion));
            builder.AppendLine(string.Format("[{0} Version {1}]", Product, InformationalVersion));
            builder.AppendLine(Copyright);
            
            return builder.ToString();
        }
    }
}
